package com.hup.utils.swing.frame;

import com.hup.utils.swing.FrameUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * {@link BaseWindow}
 *
 * @author hugan
 * @date 2020/4/10
 */
@Log4j2
public class BaseFrame extends JFrame implements BaseWindow {

    @Setter
    @Getter
    private String baseTitle;
    /**
     * 是否为单例窗口,默认true;
     * 使用{@link SingletonWindowHelper#getWindow(Class)}获取窗口对象
     */
    @Getter
    private boolean singleton = true;

    public BaseFrame(String title) {
        super(title);
        setBaseTitle(title);
        onCreate();
    }

    @Override
    public void onCreate() {
        initIcon();

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                boolean dispose = BaseFrame.this.onWindowClosing(e);
                if (dispose) dispose();
            }
        });
        FrameUtil.addVisibleListener(this, this);

        if (isSingleton()) SingletonWindowHelper.addWindow(this);
    }

    @Override
    public void onShown() {

    }

    /**
     * @return 是否dispose窗口, 默认true
     */
    @Override
    public boolean onWindowClosing(WindowEvent e) {
        return true;
    }

    /**
     * 应该不用重写本方法的, 前有 {@link #onWindowClosing(WindowEvent)},后有 {@link #onHidden(boolean)}
     */
    @Override
    public final void dispose() {
        super.dispose();
        if (isSingleton()) SingletonWindowHelper.removeWindow(this);
    }

    /**
     * 窗口关闭后的回调
     *
     * @param dispose true-点关闭按钮,dispose();false-setVisible(false)
     */
    @Override
    public void onHidden(boolean dispose) {
    }

    @Override
    public void setSingleton(boolean singleton) {
        this.singleton = singleton;
        if (!isSingleton()) SingletonWindowHelper.removeWindow(this);
    }

}
